<template>
  <div class="batch-schedule-handle">
    <el-form :model="batchForm" label-width="100px">
      <el-form-item label="科室" required>
        <el-tree-select 
          v-model="batchForm.departmentId" 
          placeholder="请选择科室"
          @change="handleDepartmentChange"
          style="width: 100%"
          :data="departmentTree"
          node-key="id"
          :props="{
            label: 'name',
            value: 'id',
            children: 'children'
          }"
          check-strictly
          clearable
          filterable
        />
      </el-form-item>
      <el-form-item label="医生" required>
        <el-select 
          v-model="batchForm.doctorIds" 
          placeholder="请选择医生"
          multiple
          style="width: 100%"
          :disabled="!batchForm.departmentId"
        >
          <el-option
            v-for="doctor in doctorList"
            :key="doctor.id"
            :label="doctor.name"
            :value="doctor.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" required>
        <el-date-picker
          v-model="batchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="排班模板" required>
        <el-checkbox-group v-model="batchForm.timeSlots">
          <el-checkbox :label="1">上午 (08:00-12:00)</el-checkbox>
          <el-checkbox :label="2">下午 (14:00-18:00)</el-checkbox>
          <el-checkbox :label="3">晚上 (19:00-21:00)</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="可预约数量" required>
        <el-input-number 
          v-model="batchForm.availableCount" 
          :min="1" 
          :max="100"
        />
      </el-form-item>
      <el-form-item label="生成预览">
        <el-text type="info">
          预计生成 <el-text type="primary">{{ previewCount }}</el-text> 个排班记录
        </el-text>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        批量创建
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { createSchedule } from '@/api/business'
import { getDepartmentTree, getDepartmentDoctors } from '@/api/business'

// Emit定义
const emit = defineEmits(['close'])

// 响应式数据
const submitLoading = ref(false)
const departmentTree = ref([])
const doctorList = ref([])

// 批量排班表单
const batchForm = reactive({
  departmentId: null,
  doctorIds: [],
  dateRange: [],
  timeSlots: [],
  availableCount: 20
})

// 计算预览数量
const previewCount = computed(() => {
  if (!batchForm.doctorIds.length || !batchForm.dateRange.length || !batchForm.timeSlots.length) {
    return 0
  }
  
  const startDate = new Date(batchForm.dateRange[0])
  const endDate = new Date(batchForm.dateRange[1])
  const dayCount = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1
  
  return batchForm.doctorIds.length * dayCount * batchForm.timeSlots.length
})

// 获取科室树形数据
const getDepartmentTreeData = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
  }
}

// 处理科室选择变更
const handleDepartmentChange = async (departmentId) => {
  if (!departmentId) {
    doctorList.value = []
    batchForm.doctorIds = []
    return
  }
  try {
    const response = await getDepartmentDoctors(departmentId)
    if (response.code === 200) {
      doctorList.value = response.data || []
      // 清空已选择的医生
      batchForm.doctorIds = []
    }
  } catch (error) {
    console.error('获取科室医生列表失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!batchForm.departmentId || !batchForm.doctorIds.length || 
      !batchForm.dateRange.length || !batchForm.timeSlots.length) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    submitLoading.value = true
    
    const schedules = []
    const [startDate, endDate] = batchForm.dateRange
    const currentDate = new Date(startDate)
    const endDateObj = new Date(endDate)
    
    while (currentDate <= endDateObj) {
      const dateStr = currentDate.toISOString().split('T')[0]
      
      batchForm.doctorIds.forEach(doctorId => {
        batchForm.timeSlots.forEach(timeSlot => {
          const timeMap = {
            1: { start: '08:00', end: '12:00' },
            2: { start: '14:00', end: '18:00' },
            3: { start: '19:00', end: '21:00' }
          }
          
          schedules.push({
            departmentId: batchForm.departmentId,
            doctorId,
            scheduleDate: dateStr,
            timeSlot,
            startTime: timeMap[timeSlot].start,
            endTime: timeMap[timeSlot].end,
            availableCount: batchForm.availableCount,
            status: 1
          })
        })
      })
      
      currentDate.setDate(currentDate.getDate() + 1)
    }

    // 批量创建排班
    let successCount = 0
    for (const schedule of schedules) {
      try {
        await createSchedule(schedule)
        successCount++
      } catch (error) {
        console.error('创建排班失败:', error)
      }
    }
    
    if (successCount > 0) {
      ElMessage.success(`成功创建 ${successCount} 个排班，失败 ${schedules.length - successCount} 个`)
      emit('close', 'success')
    } else {
      ElMessage.error('批量创建失败')
    }
  } catch (error) {
    console.error('批量创建失败:', error)
    ElMessage.error('批量创建失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  emit('close', 'cancel')
}

// 生命周期
onMounted(() => {
  getDepartmentTreeData()
})
</script>

<style scoped>
.batch-schedule-handle {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}
</style> 